package flirtme.activities;

import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.NavUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.ans.flirtme.R;

import flirtme.constants.Constants;
import flirtme.libraries.utils.Utils;
import flirtme.managers.UserManager;
import flirtme.model.CurrentUser;
import flirtme.server.UserProfileServices;

public class UserProfileActivity extends Activity {
	
	private static final int IMAGE_PICK = 1;
	private static final int IMAGE_CAPTURE = 2;
	private static final int DATE_DIALOG = 0;
	private static final int INTERESTS_DIALOG = 1;
	private ImageView imageView;
	private TextView userName;
	private EditText firstname;
	private EditText lastname;
	private EditText email;
	private EditText bithDate;
	private RadioButton genderMale;
	private RadioButton genderFemale;
	private Bitmap imageBitmap;
	private Drawable imageDrawable;
	HashMap<String, String> interests = null;
	
	//Date Picker
	private TextView dateDisplay;
	private ImageButton pickDateButton;
	private int dateYear;
	private int dateMonth;
	private int dateDay;	
	
	
	
	//Interests
	private Button interestsButton;
	private Boolean[] clickedInterests;
	private String[] interestsStrings;
	private boolean previousInterests [];
	        
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_profile);
		// Show the Up button in the action bar.
		setupActionBar();
		
		initializeInterestsVariables();
		loadUiComponents();
		initUiComponents();
		
		this.registerForContextMenu(this.imageView);

	}
	
	private void initializeInterestsVariables() {
		interests = new HashMap<String, String>();
		interests.put("Bares y restaurantes", "1");
		interests.put("Heladerías y Cafés", "2");
		interests.put("Salud y belleza", "3");
		interests.put("Viajes y turismo", "4");
		interests.put("Teatros", "5");
		interests.put("Cines", "6");
		interests.put("Deportes", "7");
		interests.put("Tecnologías", "8");
		interests.put("Indumentaria y calzados", "9");
		interests.put("Mascotas", "10");
		interests.put("Vehículos", "11");
		interests.put("Cursos y aprendizaje", "12");
		interests.put("Universidades", "13");
		interests.put("Librerías", "14");
		
		clickedInterests = new Boolean[interests.size()];
		interestsStrings = new String[interests.size()];
		int i = 0;
		for (String key : interests.keySet()) {
			interestsStrings[i] = key;
			clickedInterests[i] = false;
			i++;
		}
		
	}
	
	private String getInterestsString()
	{
		String interestsData = new String();
		for( int i = 0; i < interestsStrings.length; i++)
		{
			if( clickedInterests[i]){
				if (i!=0)
					interestsData = interestsData.concat(",");
				interestsData = interestsData.concat( interests.get(interestsStrings[i]) );
			}
		}
		return interestsData;
	}
	
	private void loadUiComponents() {

		this.imageView = (ImageView) this.findViewById(R.id.profile_avatar);
		this.userName = (TextView) this.findViewById(R.id.profile_username);
		this.firstname = (EditText) this.findViewById(R.id.profile_user_firstname);
		this.lastname = (EditText) this.findViewById(R.id.profile_user_lastname);
		this.email = (EditText) this.findViewById(R.id.profile_email);
		this.genderMale = (RadioButton) this.findViewById(R.id.radioButtonMale);
		this.genderFemale = (RadioButton) this.findViewById(R.id.radioButtonFemale);
	    this.dateDisplay = (TextView) findViewById(R.id.date_display);
	    this.pickDateButton = (ImageButton) findViewById(R.id.pick_date);
	    this.interestsButton = (Button) findViewById(R.id.interests_button);

	    // add a click listener to the button
	    pickDateButton.setOnClickListener(new View.OnClickListener() {
	        @SuppressWarnings("deprecation")
			public void onClick(View v) {
	            showDialog(DATE_DIALOG);
	        }
	    });
	    
	    interestsButton.setOnClickListener(new View.OnClickListener() {
	        @SuppressWarnings("deprecation")
			public void onClick(View v) {
	            showDialog(INTERESTS_DIALOG);
	        }
	    });
	}

	private void initUiComponents() {
		CurrentUser user = UserManager.instance().getUser();
		userName.setText(user.getUsername());
		firstname.setText(user.getFirstName());
		lastname.setText(user.getLastName());
		email.setText(user.getEmail());
		dateDisplay.setText(user.getBirthDay());
 		initializeRadioButtons(user.getGender());
		new LoadImageAsyncTask().execute();
		
		String birthday = user.getBirthDay();
		String parts[] = birthday.split("-");
		dateYear = Integer.parseInt( parts[0] );
		dateMonth = Integer.parseInt( parts[1] );
		dateDay = Integer.parseInt( parts[2] );
	}
	

	// updates the date in the TextView
	private void updateDateDisplay() {
		dateDisplay.setText(
					        new StringBuilder()
					                // Month is 0 based so add 1
									.append(dateDay).append("/")
					                .append(dateMonth + 1).append("/")
					                .append(dateYear).append(" ")
					         );
	}
	
	public void onInterestsClicked(View view)
	{
		
	}
	
	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener dateSetListener =
	        new DatePickerDialog.OnDateSetListener() {

	            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
	                dateYear = year;
	                dateMonth = monthOfYear;
	                dateDay = dayOfMonth;
	                updateDateDisplay();
	            }
	        };
	
	@Override
	protected Dialog onCreateDialog(int id) {
	    
		switch (id) 
		{
		    case DATE_DIALOG:
		        return new DatePickerDialog(this, dateSetListener, dateYear, dateMonth, dateDay);// dateYear, dateMonth, dateDay);
		        
		    case INTERESTS_DIALOG:
		    	return new AlertDialog.Builder( this )
						     	       .setTitle( "Interests" )
						     	       .setMultiChoiceItems( interestsStrings, previousInterests,  new OnMultiChoiceClickListener() {
										@SuppressWarnings("unused")
										@Override
										public void onClick(DialogInterface dialog, int which, boolean isChecked) {
											String str = interestsStrings[which];
											clickedInterests[which] = isChecked;
						     	    	       
										}
						     	       })
						     	       .setPositiveButton( "Save", new OnClickListener() {
						     	    	   @Override
						     	    	   public void onClick(DialogInterface dialog, int which) {
						     	    		   @SuppressWarnings("unused")
						     	    		   String finalString = getInterestsString();
						     	    	   }	
						     	    	})
						     	       .create();
		    	
		}
	    return null;
	}
	
	private void initializeImage()
	{
		String avatarUrl = UserManager.instance().getUser().getAvatarUrl();
		if (  avatarUrl != null )
			imageDrawable = Utils.createDrawableFromWebUrl(avatarUrl);//Utils.createBitmapFromUrl(avatarUrl);
	}

	private void applyEffectsForImage(Bitmap bm) {
		Canvas canvas = new Canvas();
		Paint mShadow = new Paint();
		// radius=10, y-offset=2, color=black
		mShadow.setShadowLayer(10.0f, 0.0f, 2.0f, 0xFF000000);
		// in onDraw(Canvas)
		canvas.drawBitmap(bm, 0.0f, 0.0f, mShadow);

		imageView.setImageBitmap(bm); // Display image in the View
		Animation fadeInAnimation = AnimationUtils.loadAnimation(this,
				R.anim.fade_in);
		imageView.startAnimation(fadeInAnimation);
	}

	/**
	 * Image result from camera
	 * 
	 * @param resultCode
	 * @param data
	 */
	private void imageFromCamera(int resultCode, Intent data) {

		imageBitmap = (Bitmap) data.getExtras().get("data");
		this.applyEffectsForImage(imageBitmap);
	}

	/**
	 * Image result from gallery
	 * 
	 * @param resultCode
	 * @param data
	 */
	private void imageFromGallery(int resultCode, Intent data) {

		Bundle extras = data.getExtras();
		if (extras != null) {
			imageBitmap = extras.getParcelable("data");
			imageView.setImageBitmap(imageBitmap);
		}
		// Uri selectedImage = data.getData();
		// String[] filePathColumn = { MediaStore.Images.Media.DATA };
		//
		// Cursor cursor = getContentResolver().query(selectedImage,
		// filePathColumn, null, null, null);
		// cursor.moveToFirst();
		//
		// int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		// String filePath = cursor.getString(columnIndex);
		// cursor.close();

		// this.applyEffectsForImage(BitmapFactory.decodeFile(filePath));

	}

	/**
	 * Receive the result from the startActivity
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case IMAGE_PICK:
				this.imageFromGallery(resultCode, data);
				break;
			case IMAGE_CAPTURE:
				this.imageFromCamera(resultCode, data);
				break;
			default:
				break;
			}
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.take_photo:
			Intent intent = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT,
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
			startActivityForResult(intent, IMAGE_CAPTURE);
			return true;
		case R.id.select_image:
			Intent intent1 = new Intent();
			intent1.setType("image/*");
			intent1.setAction(Intent.ACTION_GET_CONTENT);
			intent1.putExtra("crop", "true");
			intent1.putExtra("aspectX", 40); // This sets the max width.
			intent1.putExtra("aspectY", 40);
			intent1.putExtra("outputX", this.imageView.getWidth());
			intent1.putExtra("outputY", this.imageView.getHeight());
			try {

				intent1.putExtra("return-data", true);
				startActivityForResult(
						Intent.createChooser(intent1, "Complete action using"),
						IMAGE_PICK);
			} catch (ActivityNotFoundException e) {
				e.printStackTrace();
			}
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.context_chooser_picture_menu, menu);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.user_profile, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {
		getActionBar().setDisplayHomeAsUpEnabled(true);
	}	
	
	private void initializeRadioButtons(String currentGender) {
		if(currentGender == Constants.GENDER_MALE)
			onMaleActivated();
		else if (currentGender == Constants.GENDER_FEMALE)
			onFemaleActivated();
		else
		{
			genderFemale.setActivated(false);
			genderMale.setActivated(false);
		}
	}
	
	private void onMaleActivated() {
		genderMale.setChecked(true);
		genderFemale.setChecked(false);
	}
	
	private void onFemaleActivated() {
		genderMale.setChecked(false);
		genderFemale.setChecked(true);
	}
	
	public void onRadioButtonClicked(View view) {
	    // Is the button now checked?
	    boolean checked = ((RadioButton) view).isChecked();
	    
	    // Check which radio button was clicked
	    switch(view.getId()) {
	        case R.id.radioButtonMale:
	            if (checked)
	            	onMaleActivated();
	            break;
	        case R.id.radioButtonFemale:
	            if (checked)
	            	onFemaleActivated();
	            break;
	    }
	}
	
	private String getNewGender()
	{
		if(genderMale.isChecked())
			return Constants.GENDER_MALE;
		else if(genderFemale.isChecked())
			return Constants.GENDER_FEMALE;
		else 
			return Constants.GENDER_UNDEFINED;
	}
	
	public void onClickSaveChanges(View v) 
	{	
		//Save locally
		this.save();
		//Save on server
		UserProfileServices.callEditProfileService(this, imageBitmap, getInterestsString());
	}
	
	public void onClickCancel(View v)
	{
		goToMainActivity();
	}
	
	private void goToMainActivity()
	{
		Intent intent = new Intent(this, MainMenuActivity.class);
		startActivity(intent);
	}
	
	public void save() {
		String birthday = Integer.toString(dateYear) + "-" + Integer.toString(dateMonth) + "-" + Integer.toString(dateDay);
		UserManager um = UserManager.instance();
		um.updateUserData(  userName.getText().toString(),
							firstname.getText().toString(),
							lastname.getText().toString(),
							email.getText().toString(),
							getNewGender(),
							birthday);
  		um.setProfileCreated(true);
		um.saveCurrentUserPreferences((Context) this);
	}
	
	@Override
	public void onBackPressed() { // Ver si esto trae efectos no deseados
		Intent intent=new Intent(this, MainMenuActivity.class);
		startActivity(intent);
		UserProfileActivity.this.finish();
	}
	
	class LoadImageAsyncTask extends AsyncTask<Void, Void, Void>
	{
		Context _context;
	    ProgressDialog _ProgressDialog;
	    
	    @Override
	    protected void onPostExecute(Void result) {
//	    	_ProgressDialog.dismiss();
			if( imageDrawable != null)
				imageView.setImageDrawable(imageDrawable);
	    }

	    @Override
	    protected void onPreExecute() {
//	        _ProgressDialog = ProgressDialog.show(UserProfileActivity.this, 
//	                                        "Loading profile image...", "loading");
	    }

	    @Override
	    protected Void doInBackground(Void... params) {
	    	initializeImage();
	        return null;
	    }
	}
}
